package api

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetApiListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiListLogic {
	return &GetApiListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetApiListLogic) GetApiList(in *backend.ApiListReq) (*backend.ApiListResp, error) {
	// logrus.Info(fmt.Sprintf("ApiListReq: %+v", in))

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order string = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.SysAPIColumns.ID+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.SysAPIColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	filterMap := make(map[string]map[string][]any)
	if in.Ids != nil {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) > 0 {
			filterMap[model.SysAPIColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
		}
	}
	if !restricted {
		page = in.Page
		pageSize = in.PageSize
	}

	statusIn := modelx.UniqueInterfaces(stati, 32)
	statusMap := make(map[string][]any)
	if len(statusIn) > 0 {
		statusMap["in"] = statusIn
	}
	if in.Status != nil {
		statusMap["equalTo"] = []any{*in.Status}
	}
	filterMap[model.SysAPIColumns.Status] = statusMap

	if in.Path != nil && len(strings.TrimSpace(*in.Path)) > 0 {
		filterMap[model.SysAPIColumns.Path] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Path)},
		}
	}
	if in.Description != nil && len(strings.TrimSpace(*in.Description)) > 0 {
		filterMap[model.SysAPIColumns.Description] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Description)},
		}
	}
	if in.Group != nil && len(strings.TrimSpace(*in.Group)) > 0 {
		filterMap[model.SysAPIColumns.APIGroup] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Group)},
		}
	}
	if in.Method != nil {
		filterMap[model.SysAPIColumns.Method] = map[string][]any{
			"equalTo": []any{*in.Method},
		}
	}
	if in.Required != nil {
		filterMap[model.SysAPIColumns.IsRequired] = map[string][]any{
			"equalTo": []any{*in.Required},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThan"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThanOrEqualTo"] = endTimeIn
	}
	filterMap[model.SysAPIColumns.CreatedAt] = createdAtMap

	// logrus.Info(fmt.Sprintf("filterMap: %+v", filterMap))

	res, count, err := l.svcCtx.SysApi.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  strings.Join(orderBys, ","),
	}, 1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp := &backend.ApiListResp{
		Total: uint64(count),
	}
	for _, v := range res {
		resp.List = append(resp.List, &backend.ApiInfo{
			Id:          pointy.GetPointer(v.ID),
			Path:        pointy.GetPointer(v.Path),
			Description: pointy.GetPointer(v.Description),
			Group:       pointy.GetPointer(v.APIGroup),
			Method:      pointy.GetPointer(v.Method),
			Required:    pointy.GetPointer(uint32(v.IsRequired)),
			Status:      pointy.GetPointer(uint32(v.Status)),
			CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
			UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
		})
	}

	return resp, nil
}
